package com.hzdl.library.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决全站乱码问题，处理所有的请求
 */
@WebFilter("/*")
public class loginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse rep, FilterChain filterChain) throws IOException, ServletException {
        //将父接口转为子接口
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) rep;
        //获取请求方法
        String method = request.getMethod();
        //解决post请求中文数据乱码问题
        if(method.equalsIgnoreCase("post")){
            request.setCharacterEncoding("utf-8");
        }
        //处理响应乱码
        response.setContentType("text/html;charset=utf-8");
//        System.out.println(request.getRequestURI());
        String str = request.getRequestURI();
        String sub = "";
        if (!"/".equals(str)) {
            sub = str.substring(str.lastIndexOf("/") + 1);
        }
        String sub2 = sub.substring(sub.lastIndexOf(".") + 1);
//        System.out.println(sub);
        if ("".equals(sub) || "index.html".equals(sub) || "login".equals(sub) || request.getSession().getAttribute("readerInfo") != null || request.getSession().getAttribute("admin_id") != null || "js".equals(sub2) || "css".equals(sub2) || "jpg".equals(sub2) || "jpeg".equals(sub2) || "png".equals(sub2) || "gif".equals(sub2) || "mp4".equals(sub2) || "mp3".equals(sub2)){
            filterChain.doFilter(request, response);
        }else {
            response.sendRedirect(request.getContextPath() + "/index.html");
        }
    }

    @Override
    public void destroy() {

    }
}
